const mongoose = require('mongoose');

const DeviceSchema = new mongoose.Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true
    },
    deviceId: {
      type: String,
      required: true,
      trim: true
    },
    name: {
      type: String,
      required: true,
      trim: true
    },
    customName: {
      type: String,
      default: '',
      trim: true
    },
    type: {
      type: String,
      enum: ['glucose', 'bloodPressure', 'weight'],
      required: true
    },
    model: {
      type: String,
      default: ''
    },
    manufacturer: {
      type: String,
      default: ''
    },
    firmware: {
      type: String,
      default: ''
    },
    lastSyncDate: {
      type: Date,
      default: null
    },
    isActive: {
      type: Boolean,
      default: true
    },
    connectionStatus: {
      type: String,
      enum: ['connected', 'disconnected', 'pairing'],
      default: 'connected'
    },
    metadata: {
      type: Object,
      default: {}
    }
  },
  {
    timestamps: true
  }
);

// 复合索引确保用户的设备ID唯一
DeviceSchema.index({ user: 1, deviceId: 1 }, { unique: true });

// 自动更新上次同步时间
DeviceSchema.methods.updateSyncTime = function() {
  this.lastSyncDate = new Date();
  return this.save();
};

// 更新设备自定义名称
DeviceSchema.methods.updateCustomName = function(newName) {
  this.customName = newName;
  return this.save();
};

// 设备是否属于指定用户
DeviceSchema.statics.belongsToUser = async function(deviceId, userId) {
  const device = await this.findOne({ deviceId, user: userId });
  return !!device;
};

// 获取用户的所有设备
DeviceSchema.statics.getUserDevices = function(userId, type = null) {
  const query = { user: userId, isActive: true };
  if (type) {
    query.type = type;
  }
  return this.find(query).sort({ createdAt: -1 });
};

module.exports = mongoose.model('Device', DeviceSchema); 